package com.fsg.user.provider;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.webresources.FileResource;
import org.apache.http.client.entity.InputStreamFactory;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.apache.tomcat.util.security.MD5Encoder;
import org.apache.xmlbeans.impl.schema.FileResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.fsg.common.response.ResultBean;
import com.fsg.common.utils.MD5;
import com.fsg.user.model.ExcelReadInfo;
import com.fsg.user.model.GAPDemo;
import com.fsg.user.service.OrderGpsService;
import com.fsg.user.service.UserService;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class GAPController {

	@Autowired
	UserService userService;

	/**
	 * B系统 处理excel文件
	 * @param file
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@PostMapping(value = "/importData")
	@ApiOperation(value = "导入数据")
	public ResultBean<Object> improtData(@RequestParam("file") MultipartFile file,HttpServletResponse response ) throws IOException {
		//上传并保存文件
		List<GAPDemo>  gAPDemoList  =new ArrayList<>();
		ExcelReadInfo excelReadInfo =new ExcelReadInfo();

		EasyExcel.read(file.getInputStream(), GAPDemo.class, new AnalysisEventListener<GAPDemo>() {
			@Override
			public void invoke(GAPDemo data, AnalysisContext context) {
				//GAPController.invokeMethod();
				log.info("解析数据{}",data);
				excelReadInfo.setSheetName(context.getCurrentSheet().getSheetName());
				//错误信息
				data.setErrInfo("思思是个小猪蹄");
				excelReadInfo.setIsHasErr(true);
				gAPDemoList.add(data);
			}
			@Override
			public void doAfterAllAnalysed(AnalysisContext context) {
				log.info("解析数据完成{}",gAPDemoList);
				//操作
			}
		}).ignoreEmptyRow(true).autoTrim(true).sheet().doRead();
		//
		log.info("解析数据保存",gAPDemoList);
		//是否包含错误
		if(!excelReadInfo.getIsHasErr()) {
			return new  ResultBean<>(ResultBean.SUCCESS.getBytes());	
		}
		String fileName= file.getOriginalFilename();
		//设置文件ContentType类型
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName );
		EasyExcel.write(response.getOutputStream(), GAPDemo.class).sheet(excelReadInfo.getSheetName()).doWrite(gAPDemoList);
		return new ResultBean(true);
	}

	@Autowired
	RestTemplate restTemplate;

	/**
	 * B系统接口地址
	 */
	String url ="http://127.0.0.1:21001/importData";	
	/**
	 * A系统 接收文件上传系统
	 * @param file
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	@ApiOperation(value = "导入数据")
	public ResultBean<Object> upload(@RequestParam("file") MultipartFile file,HttpServletResponse response ) throws IOException {
		if (ObjectUtils.isEmpty(file) || file.getSize() == 0L) {
			//throw new FileImportException(ExceptionEnum.PARAM_EMPTY.getCode(), ExceptionEnum.PARAM_EMPTY.getArgMessage("文件"));
		}
		String extString = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		if (!".xls".equals(extString) && !".xlsx".equals(extString) ) {
			//throw new FileImportException(ExceptionEnum.PARAM_FORMAT_EX.getCode(), ExceptionEnum.PARAM_FORMAT_EX.getArgMessage(file.getOriginalFilename()));
		}
		//MultipartFileResource MultipartFileResource =new MultipartFileResource();
		MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
		param.add("file", file.getResource());  //服务端MultipartFile uploadFile
		ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity(url,param,byte[].class);
		String res =new String(responseEntity.getBody());
		if(res.equals(ResultBean.SUCCESS)) {
			return new ResultBean<Object>();
		}
		//设置文件ContentType类型
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + file.getOriginalFilename());
		InputStream inputStream =null;
		OutputStream outputStream =null;
		try {
			inputStream =new ByteArrayInputStream(responseEntity.getBody());
			outputStream = response.getOutputStream();
			IOUtils.copy(inputStream, response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			IOUtils.closeQuietly(inputStream);
			IOUtils.closeQuietly(outputStream);
		}
		return new ResultBean<Object>();
	}

}
